//
//  DKAuthFaceView.m
//  DanKU
//
//  Created by 吴斌 on 2023/12/5.
//

#import "DKAuthFaceView.h"
#import "DKAuthFailView.h"
#import "DKAuthFaceLoadView.h"
@interface DKAuthFaceView ()<AVCapturePhotoCaptureDelegate>
@property (nonatomic, strong)AVCaptureSession * captureSession;
@property (nonatomic, strong)AVCaptureDevice  * captureDevice;
@property (nonatomic, strong)AVCaptureDeviceInput * captureDeviceInput;
@property (nonatomic, strong)AVCapturePhotoOutput * photoOutput;
@property (nonatomic, strong)AVCaptureVideoPreviewLayer * previewLayer;
@property (nonatomic, strong)AVCapturePhotoSettings * photoSettings;
@property (nonatomic, assign)AVCaptureDevicePosition  position;

@property (nonatomic, strong)UIImageView * dk_photoImgView;

@end

@implementation DKAuthFaceView
-(AVCaptureSession *)captureSession{
    if(!_captureSession){
        _captureSession = [[AVCaptureSession alloc] init];
        if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
            _captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
        }
    }
    return _captureSession;
}
-(AVCaptureDevice *)captureDevice{
    if(!_captureDevice){
        _captureDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionFront];
    }
    return _captureDevice;
}
-(AVCaptureDeviceInput *)captureDeviceInput{
    if(!_captureDeviceInput){
        _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:nil];
    }
    return _captureDeviceInput;
}
-(AVCapturePhotoOutput *)photoOutput{
    if(!_photoOutput){
        _photoOutput = [[AVCapturePhotoOutput alloc] init];
    }
    return _photoOutput;
}
-(AVCaptureVideoPreviewLayer *)previewLayer{
    if(!_previewLayer){
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer.frame = self.bounds;
    }
    return _previewLayer;
}
-(instancetype)init{
    if(self == [super init]){
        [self makeFunView];
        [self makePhotoAuth];
    }
    return self;
}
- (void)makePhotoAuth{
    //检查照相机权限
    WeakSelf(self)
    [DKAuthorityHelper requestCameraAuthorization:^(DKAuthorizationStatus status) {
        switch (status) {
            case DKAuthorizationStatusAuthorized://已授权
            {
                [weakSelf.layer insertSublayer:weakSelf.previewLayer atIndex:0];
                if([weakSelf.captureSession canAddInput:weakSelf.captureDeviceInput]){
                    [weakSelf.captureSession addInput:weakSelf.captureDeviceInput];
                }
                if([weakSelf.captureSession canAddOutput:weakSelf.photoOutput]){
                    [weakSelf.captureSession addOutput:weakSelf.photoOutput];
                }
                [weakSelf startRunning];
            }
                break;
            default:{
                UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"" message:@"Your camera permission is disabled. In order to utilize the camera for tasks like taking pictures of the ID card, changing your avatar, or verifying certificates. turn on the applied camera permission in settings." preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                [alertCtrl addAction:cancelAction];
                [alertCtrl addAction:okAction];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController presentViewController:alertCtrl animated:YES completion:nil];
                });
            }
            break;
        }
    }];
}
- (void)makeFunView{
    self.dk_photoImgView = [[UIImageView alloc] init];
    self.dk_photoImgView.userInteractionEnabled = YES;
    self.dk_photoImgView.image = DK_GetImage(@"dk_FaceAuthEnticationBg");
    self.dk_photoImgView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.dk_photoImgView];
    [self.dk_photoImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
}
//开始运行
- (void)startRunning{
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self.captureSession startRunning];
        self.dk_photoImgView.image = nil;
//    });
}
//停止运行
- (void)stopRunning{
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self.captureSession stopRunning];
//    });
}
//拍照
- (void)startCamera{
    self.photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecTypeJPEG}];
    if(!self.previewLayer||!self.photoOutput||!self.photoSettings){
        return;
    }
    if(self.captureSession.isRunning == YES){
        [self.photoOutput capturePhotoWithSettings:self.photoSettings delegate:self];
    }
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if(!error){
        NSData *imageData = [photo fileDataRepresentation];
        UIImage *image = [UIImage imageWithData:imageData];
        self.dk_photoImgView.image = image;
        [self makeUploadPan];
    }
}
- (void)makeUploadPan{
    WeakSelf(self)
    __block DKAuthFaceLoadView * dk_AuthFaceLoadView = [DKAuthFaceLoadView dk_ShowAuthFaceLoadAlertView:^{
//        UIImage *rotationImage = [UIImage imageWithCGImage:self.dk_photoImgView.image.CGImage scale:2.0 orientation:UIImageOrientationLeft];
        NSData *imageData = [NSString changeImageSizeForData:self.dk_photoImgView.image toByte:300000];
        NSMutableDictionary *ossLiveBase64Dic = [[NSMutableDictionary alloc] init];
        [ossLiveBase64Dic setValue:@"" forKey:@"actionId"];
        [ossLiveBase64Dic setValue:self.dk_AuthLivenConfigMdl.livenChannel forKey:@"channelEnum"];
        [DKPublicHttp  apiOssLiveBase64ForAPI:ossLiveBase64Dic withData:imageData complete:^(DKAuthLiveBase64Model * _Nonnull dk_AuthLiveBase64Mdl) {//认证成功
            NSDictionary *preLivenessDic = @{@"livenessId":dk_AuthLiveBase64Mdl.livenessId};
            [DKPublicHttp apiPreLivenessForAPI:preLivenessDic complete:^{//活体预处理
                if(weakSelf.FaceAuthScuessBlock){
                    weakSelf.dk_photoImgView.image = nil;
                    weakSelf.FaceAuthScuessBlock(dk_AuthLiveBase64Mdl);
                    [dk_AuthFaceLoadView.dk_AuthFaceLoadViewPop dismiss];
                }
            }];
        } fail:^(NSString * _Nonnull msg) {//认证失败
            [DKAuthFailView dk_ShowAuthFailAlertView:^{
                if(weakSelf.FaceAuthFailBlock){
                    weakSelf.dk_photoImgView.image = nil;
                    [dk_AuthFaceLoadView.dk_AuthFaceLoadViewPop dismiss];
                    weakSelf.FaceAuthFailBlock(msg);
                }
            }];
        }];
    }];
    
}
@end
